import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import '../../../common/models/index.dart';

import 'index.dart';
import 'theme.dart';

class YanshouAssessmentDetialPage extends StatefulWidget {
  const YanshouAssessmentDetialPage({super.key});

  @override
  State<YanshouAssessmentDetialPage> createState() => _YanshouAssessmentDetialPageState();
}

class _YanshouAssessmentDetialPageState extends State<YanshouAssessmentDetialPage> {
  int _selectedIndex = 0;

  YanshouAssessmentDetialController get controller => Get.find<YanshouAssessmentDetialController>();

  // Tab 1: 项目基本信息
  Widget _buildProjectInfoTab() {
    return Obx(() {
      if (controller.isLoading.value) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      
      if (controller.errorMessage.value.isNotEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.error_outline, size: 48, color: Colors.red),
              const SizedBox(height: 16),
              Text(
                controller.errorMessage.value,
                style: const TextStyle(fontSize: 16, color: Colors.red),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: controller.refreshProjectDetail,
                child: const Text('重试'),
              ),
            ],
          ),
        );
      }
      
      if (controller.project.value == null) {
        return const Center(
          child: Text('暂无项目信息'),
        );
      }

      final project = controller.project.value!;
      return RefreshIndicator(
        onRefresh: controller.refreshProjectDetail,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildProjectHeader(project),
              const SizedBox(height: 8),
              _buildProjectInfo(project),
              const SizedBox(height: 8),
              _buildProjectDetails(project),
            ],
          ),
        ),
      );
    });
  }

  // Tab 2: 验收专家列表
  Widget _buildExpertsTab() {
    return Obx(() {
      if (controller.isLoading.value) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      
      return RefreshIndicator(
        onRefresh: controller.refreshProjectExperts,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: _buildProjectExperts(),
        ),
      );
    });
  }
  
  // Tab 3: 验收归档资料
  Widget _buildFilesTab() {
    return Obx(() {
      if (controller.isLoadingFiles.value) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      
      return RefreshIndicator(
        onRefresh: controller.refreshAcceptanceFiles,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: _buildAcceptanceFilesList(),
        ),
      );
    });
  }

  // 项目头部信息
  Widget _buildProjectHeader(ProjectModel project) {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 6, 10, 6),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(YanshouTheme.radiusXl),
        gradient: const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFFFFF5F5),  // 淡红色背景
            Colors.white,
          ],
        ),
        boxShadow: [YanshouTheme.cardShadow],
      ),
      padding: const EdgeInsets.all(12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              // 渐变装饰线
              Container(
                width: 3,
                height: 20,
                decoration: YanshouTheme.gradientLineDecoration,
              ),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  project.projectName ?? '未知项目',
                  style: YanshouTheme.titleStyle,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),
          Row(
            children: [
              // 项目状态标签
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: ProjectModel.getStatusColorByValue(project.status).withOpacity(0.1),
                  borderRadius: BorderRadius.circular(YanshouTheme.radiusLg),
                  border: Border.all(
                    color: ProjectModel.getStatusColorByValue(project.status),
                    width: 1.5,
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 6,
                      height: 6,
                      decoration: BoxDecoration(
                        color: ProjectModel.getStatusColorByValue(project.status),
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SizedBox(width: 4),
                    Text(
                      ProjectModel.getStatusTextByValue(project.status),
                      style: TextStyle(
                        color: ProjectModel.getStatusColorByValue(project.status),
                        fontSize: YanshouTheme.textSm,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 8),
              if (project.budgetAmount != null && project.budgetAmount.toString() != 'null')
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: YanshouTheme.warningColor.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(YanshouTheme.radiusLg),
                    border: Border.all(
                      color: YanshouTheme.warningColor,
                      width: 1,
                    ),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        Icons.account_balance_wallet,
                        size: YanshouTheme.iconSm,
                        color: YanshouTheme.warningColor,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        '${project.budgetAmount}万元',
                        style: TextStyle(
                          fontSize: YanshouTheme.textSm,
                          fontWeight: FontWeight.w600,
                          color: YanshouTheme.warningColor,
                        ),
                      ),
                    ],
                  ),
                ),
            ],
          ),
        ],
      ),
    );
  }

  // 项目基本信息
  Widget _buildProjectInfo(ProjectModel project) {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 6, 10, 6),
      padding: const EdgeInsets.all(10),
      decoration: YanshouTheme.cardDecoration,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              // 渐变图标
              Container(
                padding: const EdgeInsets.all(5),
                decoration: YanshouTheme.gradientIconDecoration,
                child: const Icon(
                  Icons.info_outline_rounded,
                  color: Colors.white,
                  size: 14,
                ),
              ),
              const SizedBox(width: 6),
              Text(
                '基本信息',
                style: YanshouTheme.subtitleStyle,
              ),
            ],
          ),
          const SizedBox(height: 10),
          // 项目状态信息（高亮显示）
          Container(
            padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 10),
            margin: const EdgeInsets.only(bottom: 8),
            decoration: BoxDecoration(
              color: ProjectModel.getStatusColorByValue(project.status).withOpacity(0.08),
              borderRadius: BorderRadius.circular(YanshouTheme.radiusMd),
              border: Border.all(
                color: ProjectModel.getStatusColorByValue(project.status).withOpacity(0.3),
                width: 1,
              ),
            ),
            child: Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(4),
                  decoration: BoxDecoration(
                    color: ProjectModel.getStatusColorByValue(project.status).withOpacity(0.15),
                    borderRadius: BorderRadius.circular(YanshouTheme.radiusSm),
                  ),
                  child: Icon(
                    Icons.info_outline,
                    size: YanshouTheme.iconSm,
                    color: ProjectModel.getStatusColorByValue(project.status),
                  ),
                ),
                const SizedBox(width: 8),
                Text(
                  '项目状态',
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: YanshouTheme.textBase,
                    color: ProjectModel.getStatusColorByValue(project.status),
                  ),
                ),
                const Spacer(),
                Text(
                  '${ProjectModel.getStatusTextByValue(project.status)} (${project.status})',
                  style: TextStyle(
                    fontSize: YanshouTheme.textBase,
                    fontWeight: FontWeight.bold,
                    color: ProjectModel.getStatusColorByValue(project.status),
                  ),
                ),
              ],
            ),
          ),
          _buildInfoRow('申报部门', project.declareDepartment != 'null' ? project.declareDepartment : null, Icons.business),
          _buildInfoRow('项目编号', project.projectNo != 'null' ? project.projectNo : null, Icons.tag),
          _buildInfoRow('申报时间', project.declareTime != 'null' ? project.declareTime : null, Icons.calendar_today),
          _buildInfoRow('项目联系人', project.projectContact != 'null' ? project.projectContact : null, Icons.person),
          _buildInfoRow('联系电话', project.phone != 'null' ? project.phone : null, Icons.phone),
          _buildInfoRow('项目经理', project.projectManager != 'null' ? project.projectManager : null, Icons.manage_accounts),
        ],
      ),
    );
  }

  // 项目详细信息
  Widget _buildProjectDetails(ProjectModel project) {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 6, 10, 6),
      padding: const EdgeInsets.all(10),
      decoration: YanshouTheme.cardDecoration,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              // 渐变图标
              Container(
                padding: const EdgeInsets.all(5),
                decoration: YanshouTheme.gradientIconDecoration,
                child: const Icon(
                  Icons.description_outlined,
                  color: Colors.white,
                  size: 14,
                ),
              ),
              const SizedBox(width: 6),
              Text(
                '项目详情',
                style: YanshouTheme.subtitleStyle,
              ),
            ],
          ),
          const SizedBox(height: 10),
          if (project.background?.isNotEmpty == true && project.background != 'null') ...[
            _buildDetailSection('项目背景', project.background!),
            const SizedBox(height: 6),
          ],
          if (project.requirements?.isNotEmpty == true && project.requirements != 'null') ...[
            _buildDetailSection('项目要求', project.requirements!),
            const SizedBox(height: 6),
          ],
          if (project.objectives?.isNotEmpty == true && project.objectives != 'null') ...[
            _buildDetailSection('项目目标', project.objectives!),
            const SizedBox(height: 6),
          ],
          if (project.implementation?.isNotEmpty == true && project.implementation != 'null') ...[
            _buildDetailSection('项目实施', project.implementation!),
            const SizedBox(height: 6),
          ],
          if (project.reviewSuggestions?.toString().isNotEmpty == true && project.reviewSuggestions.toString() != 'null') ...[
            _buildDetailSection('评审建议', project.reviewSuggestions.toString()),
          ],
        ],
      ),
    );
  }

  // 信息行
  Widget _buildInfoRow(String label, String? value, IconData? icon) {
    // 处理null值或"null"字符串
    final displayValue = (value?.isNotEmpty == true && value != 'null') ? value! : '暂无';
    final isValid = value?.isNotEmpty == true && value != 'null';
    
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 5),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (icon != null) ...[
            Container(
              padding: const EdgeInsets.all(4),
              decoration: BoxDecoration(
                color: const Color(0xFFFF6B6B).withOpacity(0.1),
                borderRadius: BorderRadius.circular(YanshouTheme.radiusSm),
              ),
              child: Icon(
                icon,
                size: YanshouTheme.iconSm,
                color: const Color(0xFFFF6B6B),
              ),
            ),
            const SizedBox(width: 8),
          ],
          Expanded(
            child: RichText(
              text: TextSpan(
                children: [
                  TextSpan(
                    text: '$label：',
                    style: YanshouTheme.labelStyle,
                  ),
                  TextSpan(
                    text: displayValue,
                    style: isValid 
                        ? YanshouTheme.valueStyle 
                        : YanshouTheme.captionStyle,
                  ),
                ],
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  // 详情节
  Widget _buildDetailSection(String title, String content) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(
              width: 3,
              height: 14,
              decoration: YanshouTheme.gradientLineDecoration,
            ),
            const SizedBox(width: 6),
            Text(
              title,
              style: TextStyle(
                fontWeight: FontWeight.w600,
                fontSize: YanshouTheme.textBase,
                color: YanshouTheme.textSecondary,
              ),
            ),
          ],
        ),
        const SizedBox(height: 6),
        Container(
          width: double.infinity,
          padding: const EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: YanshouTheme.backgroundColor,
            borderRadius: BorderRadius.circular(YanshouTheme.radiusMd),
            border: Border.all(
              color: YanshouTheme.dividerColor,
              width: 0.5,
            ),
          ),
          child: Text(
            content,
            style: TextStyle(
              fontSize: YanshouTheme.textBase,
              height: 1.5,
              color: YanshouTheme.textPrimary,
            ),
          ),
        ),
      ],
    );
  }

  // 项目专家列表
  Widget _buildProjectExperts() {
    return Obx(() {
      return Container(
        margin: const EdgeInsets.fromLTRB(10, 6, 10, 6),
        padding: const EdgeInsets.all(10),
        decoration: YanshouTheme.cardDecoration,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                // 渐变图标
                Container(
                  padding: const EdgeInsets.all(5),
                  decoration: YanshouTheme.gradientIconDecoration,
                  child: const Icon(
                    Icons.people_outline_rounded,
                    color: Colors.white,
                    size: 14,
                  ),
                ),
              const SizedBox(width: 6),
              Text(
                '验收专家列表',
                style: YanshouTheme.subtitleStyle,
              ),
              const Spacer(),
              if (controller.isLoadingExperts.value)
                SizedBox(
                  width: 14,
                  height: 14,
                  child: CircularProgressIndicator(strokeWidth: 2, color: Colors.blue.shade600),
                )
              else
                IconButton(
                  icon: Icon(Icons.refresh, size: 16, color: Colors.grey.shade600),
                  onPressed: controller.refreshProjectExperts,
                  tooltip: '刷新专家列表',
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(),
                ),
            ],
          ),
          const SizedBox(height: 8),
          
          if (controller.expertErrorMessage.value.isNotEmpty)
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Colors.red.shade50,
                borderRadius: BorderRadius.circular(6),
                border: Border.all(color: Colors.red.shade200),
              ),
              child: Row(
                children: [
                  Icon(Icons.error_outline, color: Colors.red.shade600, size: 16),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      controller.expertErrorMessage.value,
                      style: TextStyle(color: Colors.red.shade600, fontSize: 12),
                    ),
                  ),
                  TextButton(
                    onPressed: controller.refreshProjectExperts,
                    style: TextButton.styleFrom(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      minimumSize: Size.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                    child: const Text('重试', style: TextStyle(fontSize: 12)),
                  ),
                ],
              ),
            )
          else if (controller.projectExperts.isEmpty && !controller.isLoadingExperts.value)
            Container(
              padding: const EdgeInsets.all(10),
              child: Row(
                children: [
                  Icon(Icons.info_outline, color: Colors.grey.shade600, size: 16),
                  const SizedBox(width: 8),
                  Text(
                    '暂无验收专家信息',
                    style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
                  ),
                ],
              ),
            )
          else
            Builder(
              builder: (context) {
                // 将当前登录的专家排在第一位
                final experts = controller.projectExperts.toList();
                final currentExpertId = controller.currentExpertId;
                
                // 找到当前专家的索引
                final currentExpertIndex = experts.indexWhere(
                  (expert) => expert.expertId == currentExpertId,
                );
                
                // 如果找到当前专家且不在第一位，则移到第一位
                if (currentExpertIndex > 0) {
                  final currentExpert = experts.removeAt(currentExpertIndex);
                  experts.insert(0, currentExpert);
                }
                
                return ListView.separated(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: experts.length,
                  separatorBuilder: (context, index) => Divider(height: 12, color: Colors.grey.shade200),
                  itemBuilder: (context, index) {
                    final expert = experts[index];
                    return _buildExpertItem(expert);
                  },
                );
              },
            ),
          ],
        ),
      );
    });
  }

  // 专家项目
  Widget _buildExpertItem(ProjectExpert expert) {
    final isCurrentExpert = expert.expertId == controller.currentExpertId;
    final hasChecked = expert.checkStatus == 1;
    
    return Container(
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: isCurrentExpert 
            ? const Color(0xFFFFF5F5)  // 淡红色背景
            : YanshouTheme.backgroundColor,
        borderRadius: BorderRadius.circular(YanshouTheme.radiusLg),
        border: Border.all(
          color: isCurrentExpert 
              ? const Color(0xFFFF6B6B).withOpacity(0.3)
              : YanshouTheme.dividerColor,
          width: isCurrentExpert ? 1.5 : 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 专家基本信息行
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 专家头像（带渐变）
              Container(
                decoration: isCurrentExpert
                    ? BoxDecoration(
                        shape: BoxShape.circle,
                        boxShadow: [
                          BoxShadow(
                            color: const Color(0xFFD84545).withOpacity(0.3),
                            blurRadius: 8,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      )
                    : null,
                child: Container(
                  width: 32,
                  height: 32,
                  decoration: BoxDecoration(
                    gradient: isCurrentExpert
                        ? YanshouTheme.primaryGradient
                        : null,
                    color: isCurrentExpert ? null : const Color(0xFFFFE0E0),
                    shape: BoxShape.circle,
                  ),
                  child: Center(
                    child: Text(
                      expert.expertName?.isNotEmpty == true 
                          ? expert.expertName!.substring(0, 1).toUpperCase()
                          : '?',
                      style: TextStyle(
                        color: isCurrentExpert ? Colors.white : const Color(0xFFD84545),
                        fontWeight: FontWeight.bold,
                        fontSize: 14,
                      ),
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 8),
              
              // 专家信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Flexible(
                          child: Text(
                            expert.expertName ?? '未知专家',
                            style: TextStyle(
                              fontSize: YanshouTheme.textMd,
                              fontWeight: FontWeight.w600,
                              color: isCurrentExpert 
                                  ? const Color(0xFFD84545)
                                  : YanshouTheme.textPrimary,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        if (isCurrentExpert) ...[
                          const SizedBox(width: 4),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                            decoration: BoxDecoration(
                              gradient: YanshouTheme.primaryGradient,
                              borderRadius: BorderRadius.circular(YanshouTheme.radiusSm),
                              boxShadow: [
                                BoxShadow(
                                  color: const Color(0xFFD84545).withOpacity(0.3),
                                  blurRadius: 4,
                                  offset: const Offset(0, 1),
                                ),
                              ],
                            ),
                            child: const Text(
                              '我',
                              style: TextStyle(
                                fontSize: 10,
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                    const SizedBox(height: 2),
                    if (expert.corpName?.isNotEmpty == true && expert.corpName != 'null')
                      Text(
                        expert.corpName!,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    const SizedBox(height: 3),
                    if (expert.officialCapacity?.isNotEmpty == true && expert.officialCapacity != 'null')
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.orange.shade100,
                          borderRadius: BorderRadius.circular(3),
                        ),
                        child: Text(
                          expert.officialCapacity!,
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.orange.shade800,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                  ],
                ),
              ),
              
              // 状态指示器
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                decoration: BoxDecoration(
                  color: hasChecked ? Colors.green.shade50 : Colors.grey.shade200,
                  borderRadius: BorderRadius.circular(10),
                  border: Border.all(
                    color: hasChecked ? Colors.green.shade400 : Colors.grey.shade400,
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 6,
                      height: 6,
                      decoration: BoxDecoration(
                        color: hasChecked ? Colors.green : Colors.grey.shade500,
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SizedBox(width: 4),
                    Text(
                      hasChecked ? '已验收' : '待验收',
                      style: TextStyle(
                        fontSize: 10,
                        fontWeight: FontWeight.w500,
                        color: hasChecked ? Colors.green.shade700 : Colors.grey.shade700,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          
          // 如果已验收，显示验收意见和签名
          if (hasChecked) ...[
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(6),
                border: Border.all(color: Colors.grey.shade200),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 验收意见
                  if (expert.checkNote?.isNotEmpty == true && expert.checkNote != 'null') ...[
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Icon(Icons.comment_outlined, size: 12, color: Colors.blue.shade600),
                        const SizedBox(width: 4),
                        Expanded(
                          child: Text(
                            expert.checkNote!,
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey.shade800,
                              height: 1.3,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 6),
                  ],
                  
                  // 签名和时间
                  Row(
                    children: [
                      Icon(Icons.edit_note, size: 12, color: Colors.green.shade600),
                      const SizedBox(width: 4),
                      Text(
                        '已签名',
                        style: TextStyle(
                          fontSize: 11,
                          color: Colors.green.shade700,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      if (expert.checkSignTime != null && expert.checkSignTime! > 0) ...[
                        const SizedBox(width: 6),
                        Text(
                          '${_formatTimestamp(expert.checkSignTime!)}',
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.grey.shade500,
                          ),
                        ),
                      ],
                    ],
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }
  
  /// 格式化时间戳
  String _formatTimestamp(int timestamp) {
    final date = DateTime.fromMillisecondsSinceEpoch(timestamp);
    final now = DateTime.now();
    final diff = now.difference(date);
    
    if (diff.inDays > 0) {
      return '${diff.inDays}天前';
    } else if (diff.inHours > 0) {
      return '${diff.inHours}小时前';
    } else if (diff.inMinutes > 0) {
      return '${diff.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }
  
  // 验收归档文件列表
  Widget _buildAcceptanceFilesList() {
    return Obx(() {
      return Container(
        margin: const EdgeInsets.fromLTRB(10, 6, 10, 6),
        padding: const EdgeInsets.all(10),
        decoration: YanshouTheme.cardDecoration,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                // 渐变图标
                Container(
                  padding: const EdgeInsets.all(5),
                  decoration: YanshouTheme.gradientIconDecoration,
                  child: const Icon(
                    Icons.folder_outlined,
                    color: Colors.white,
                    size: 14,
                  ),
                ),
                const SizedBox(width: 6),
                Text(
                  '验收归档资料',
                  style: YanshouTheme.subtitleStyle,
                ),
                const Spacer(),
                if (controller.isLoadingFiles.value)
                  SizedBox(
                    width: 14,
                    height: 14,
                    child: CircularProgressIndicator(strokeWidth: 2, color: Colors.blue.shade600),
                  )
                else
                  IconButton(
                    icon: Icon(Icons.refresh, size: 16, color: Colors.grey.shade600),
                    onPressed: controller.refreshAcceptanceFiles,
                    tooltip: '刷新文件列表',
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                  ),
              ],
            ),
            const SizedBox(height: 8),
            
            if (controller.filesErrorMessage.value.isNotEmpty)
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.red.shade50,
                  borderRadius: BorderRadius.circular(6),
                  border: Border.all(color: Colors.red.shade200),
                ),
                child: Row(
                  children: [
                    Icon(Icons.error_outline, color: Colors.red.shade600, size: 16),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        controller.filesErrorMessage.value,
                        style: TextStyle(color: Colors.red.shade600, fontSize: 12),
                      ),
                    ),
                    TextButton(
                      onPressed: controller.refreshAcceptanceFiles,
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        minimumSize: Size.zero,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      child: const Text('重试', style: TextStyle(fontSize: 12)),
                    ),
                  ],
                ),
              )
            else if (controller.acceptanceFiles.isEmpty && !controller.isLoadingFiles.value)
              Container(
                padding: const EdgeInsets.all(10),
                child: Row(
                  children: [
                    Icon(Icons.info_outline, color: Colors.grey.shade600, size: 16),
                    const SizedBox(width: 8),
                    Text(
                      '暂无验收归档资料',
                      style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
                    ),
                  ],
                ),
              )
            else
              ListView.separated(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: controller.acceptanceFiles.length,
                separatorBuilder: (context, index) => Divider(height: 12, color: Colors.grey.shade200),
                itemBuilder: (context, index) {
                  final file = controller.acceptanceFiles[index];
                  return _buildFileItem(file);
                },
              ),
          ],
        ),
      );
    });
  }
  
  // 构建文件项
  Widget _buildFileItem(SupplierFileModel file) {
    final fileId = file.id ?? 0;
    
    return Obx(() {
      final isDownloading = controller.isDownloading[fileId] == true;
      final progress = controller.downloadProgress[fileId] ?? 0.0;
      
      return Container(
        padding: const EdgeInsets.all(10),
        decoration: BoxDecoration(
          color: YanshouTheme.backgroundColor,
          borderRadius: BorderRadius.circular(YanshouTheme.radiusLg),
          border: Border.all(
            color: YanshouTheme.dividerColor,
            width: 1,
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                // 文件图标
                Container(
                  padding: const EdgeInsets.all(6),
                  decoration: BoxDecoration(
                    gradient: YanshouTheme.infoGradient,
                    borderRadius: BorderRadius.circular(YanshouTheme.radiusSm),
                  ),
                  child: Icon(
                    _getFileIcon(file.fileName),
                    color: Colors.white,
                    size: 16,
                  ),
                ),
                const SizedBox(width: 10),
                
                // 文件信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        file.fileName ?? '未知文件',
                        style: TextStyle(
                          fontSize: YanshouTheme.textBase,
                          fontWeight: FontWeight.w600,
                          color: YanshouTheme.textPrimary,
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 4),
                      Row(
                        children: [
                          // 文件类型标签
                          if (file.fileType != null)
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                              decoration: BoxDecoration(
                                color: _getFileTypeColor(file.fileType!).withOpacity(0.1),
                                borderRadius: BorderRadius.circular(4),
                                border: Border.all(
                                  color: _getFileTypeColor(file.fileType!).withOpacity(0.3),
                                  width: 1,
                                ),
                              ),
                              child: Text(
                                _getFileTypeLabel(file.fileType!),
                                style: TextStyle(
                                  fontSize: 10,
                                  fontWeight: FontWeight.w500,
                                  color: _getFileTypeColor(file.fileType!),
                                ),
                              ),
                            ),
                          const SizedBox(width: 6),
                          Text(
                            file.fileSizeReadable,
                            style: TextStyle(
                              fontSize: YanshouTheme.textSm,
                              color: YanshouTheme.textHint,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                
                // 下载按钮或进度
                if (isDownloading)
                  SizedBox(
                    width: 40,
                    height: 40,
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        CircularProgressIndicator(
                          value: progress,
                          strokeWidth: 2,
                          valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFF9C27B0)),
                        ),
                        Text(
                          '${(progress * 100).toInt()}%',
                          style: const TextStyle(
                            fontSize: 10,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  )
                else
                  IconButton(
                    onPressed: () => controller.downloadAcceptanceFile(file),
                    icon: Container(
                      padding: const EdgeInsets.all(6),
                      decoration: BoxDecoration(
                        color: const Color(0xFF9C27B0).withOpacity(0.1),
                        borderRadius: BorderRadius.circular(YanshouTheme.radiusSm),
                      ),
                      child: const Icon(
                        Icons.download_rounded,
                        color: Color(0xFF9C27B0),
                        size: 18,
                      ),
                    ),
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                  ),
              ],
            ),
          ],
        ),
      );
    });
  }
  
  // 根据文件名获取图标
  IconData _getFileIcon(String? fileName) {
    if (fileName == null) return Icons.insert_drive_file;
    
    final ext = fileName.toLowerCase().split('.').last;
    switch (ext) {
      case 'pdf':
        return Icons.picture_as_pdf;
      case 'doc':
      case 'docx':
        return Icons.description;
      case 'xls':
      case 'xlsx':
        return Icons.table_chart;
      case 'ppt':
      case 'pptx':
        return Icons.slideshow;
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
        return Icons.image;
      case 'zip':
      case 'rar':
      case '7z':
        return Icons.folder_zip;
      default:
        return Icons.insert_drive_file;
    }
  }
  
  // 根据文件类型获取标签文本
  String _getFileTypeLabel(int fileType) {
    switch (fileType) {
      case 1:
        return '立项申请与批复资料';
      case 2:
        return '招标文件';
      case 3:
        return '中标的投标文件（正本）';
      case 4:
        return '中标通知书';
      case 5:
        return '合同文件';
      case 6:
        return '签收单';
      case 7:
        return '项目验收申请表';
      case 8:
        return '项目验收初验表';
      case 9:
        return '项目终验检查表';
      case 0:
        return '额外资料';
      default:
        return '其他资料';
    }
  }
  
  // 根据文件类型获取颜色
  Color _getFileTypeColor(int fileType) {
    switch (fileType) {
      case 1:
        return const Color(0xFF2196F3); // 蓝色 - 立项申请
      case 2:
        return const Color(0xFFFF9800); // 橙色 - 招标文件
      case 3:
        return const Color(0xFF4CAF50); // 绿色 - 投标文件
      case 4:
        return const Color(0xFFE91E63); // 粉色 - 中标通知
      case 5:
        return const Color(0xFF9C27B0); // 紫色 - 合同文件
      case 6:
        return const Color(0xFF00BCD4); // 青色 - 签收单
      case 7:
        return const Color(0xFFFF5722); // 深橙 - 验收申请
      case 8:
        return const Color(0xFF3F51B5); // 靛蓝 - 初验表
      case 9:
        return const Color(0xFF009688); // 青绿 - 终验检查表
      case 0:
      default:
        return const Color(0xFF757575); // 灰色 - 额外资料/其他
    }
  }


  // 构建按钮式Tab切换器
  Widget _buildTabSwitcher() {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 8, 10, 8),
      padding: const EdgeInsets.all(3),
      decoration: BoxDecoration(
        color: YanshouTheme.backgroundColor,
        borderRadius: BorderRadius.circular(YanshouTheme.radiusLg),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.02),
            blurRadius: 4,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: _buildTabButton(
              index: 0,
              icon: Icons.assignment,
              label: '项目信息',
            ),
          ),
          const SizedBox(width: 3),
          Expanded(
            child: _buildTabButton(
              index: 1,
              icon: Icons.people,
              label: '验收专家',
            ),
          ),
          const SizedBox(width: 3),
          Expanded(
            child: _buildTabButton(
              index: 2,
              icon: Icons.folder,
              label: '归档资料',
            ),
          ),
        ],
      ),
    );
  }

  // 构建单个Tab按钮
  Widget _buildTabButton({
    required int index,
    required IconData icon,
    required String label,
  }) {
    final isSelected = _selectedIndex == index;
    
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedIndex = index;
        });
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        padding: const EdgeInsets.symmetric(vertical: 10),
        decoration: BoxDecoration(
          gradient: isSelected ? YanshouTheme.primaryGradient : null,
          color: isSelected ? null : Colors.transparent,
          borderRadius: BorderRadius.circular(YanshouTheme.radiusMd),
          boxShadow: isSelected
              ? [
                  BoxShadow(
                    color: const Color(0xFFD84545).withOpacity(0.25),
                    blurRadius: 6,
                    offset: const Offset(0, 2),
                  ),
                ]
              : null,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              icon,
              size: 18,
              color: isSelected ? Colors.white : YanshouTheme.textHint,
            ),
            const SizedBox(width: 5),
            Text(
              label,
              style: TextStyle(
                fontSize: YanshouTheme.textMd,
                fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
                color: isSelected ? Colors.white : YanshouTheme.textHint,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 获取当前登录专家的记录
  ProjectExpert? _getCurrentExpert() {
    try {
      final currentExpertId = controller.currentExpertId;
      final experts = controller.projectExperts;
      
      // 从专家列表中找到当前专家
      for (final expert in experts) {
        if (expert.expertId == currentExpertId) {
          return expert;
        }
      }
      
      return null;
    } catch (e) {
      debugPrint('获取当前专家信息失败: $e');
      return null;
    }
  }

  // 底部验收按钮
  Widget _buildBottomButton() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.06),
            offset: const Offset(0, -2),
            blurRadius: 8,
            spreadRadius: 0,
          ),
        ],
      ),
      child: SafeArea(
        child: Obx(() {
          // 检查当前专家是否已经完成验收
          final currentExpert = _getCurrentExpert();
          final hasCompleted = currentExpert != null && currentExpert.checkStatus == 1;
          
          return Container(
            height: 46,
            decoration: BoxDecoration(
              gradient: hasCompleted 
                  ? YanshouTheme.successGradient 
                  : YanshouTheme.primaryGradient,
              borderRadius: BorderRadius.circular(YanshouTheme.radiusXl),
              boxShadow: [
                BoxShadow(
                  color: (hasCompleted 
                      ? const Color(0xFF4CAF50)
                      : const Color(0xFFD84545)
                  ).withOpacity(0.3),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: ElevatedButton.icon(
              onPressed: hasCompleted ? null : controller.onStartCheck,
              icon: Icon(
                hasCompleted ? Icons.check_circle_rounded : Icons.verified_outlined, 
                size: 20,
              ),
              label: Text(
                hasCompleted ? '已完成验收' : '提交验收',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.transparent,
                foregroundColor: Colors.white,
                shadowColor: Colors.transparent,
                elevation: 0,
                disabledBackgroundColor: Colors.transparent,
                disabledForegroundColor: Colors.white.withOpacity(0.9),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(YanshouTheme.radiusXl),
                ),
              ),
            ),
          );
        }),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<YanshouAssessmentDetialController>(
      init: YanshouAssessmentDetialController(),
      id: "yanshou_assessment_detial",
      builder: (_) {
        return Scaffold(
          backgroundColor: YanshouTheme.backgroundColor,
          appBar: AppBar(
            title: const Text("项目验收评审详情"),
            leading: IconButton(
              icon: const Icon(Icons.arrow_back_ios),
              onPressed: () => Get.back(),
            ),
            elevation: 0.5,
          ),
          body: SafeArea(
            child: Column(
              children: [
                // 按钮式Tab切换器
                _buildTabSwitcher(),
                
                // 内容区域
                Expanded(
                  child: IndexedStack(
                    index: _selectedIndex,
                    children: [
                      _buildProjectInfoTab(),
                      _buildExpertsTab(),
                      _buildFilesTab(),
                    ],
                  ),
                ),
              ],
            ),
          ),
          bottomNavigationBar: _buildBottomButton(),
        );
      },
    );
  }
}
